<template>
  <div>
    <el-dialog
      v-dialogDrag
      :before-close="closed"
      :close-on-click-modal="false"
      width="780px"
      title="节目组选择"
      :visible.sync="innerVisible"
      append-to-body>
      <el-row :gutter="10">
        <el-col :span="24">
          <!-- 列表区域 -->
          <div style="position: relative;">
            <el-row>
              <el-col :span="24">
                <el-row>
                  <el-col :span="16">
                    <span> 【{{this.scopeRow.pgm_name}}】 <time-picker inputType="readonly" v-model="sumpgmLen" style="display: inline;" /></span>
                  </el-col>
                  <el-col :span="8">
                      <el-button icon="el-icon-top" type="primary" @click="handleRowsMove('Up')" :disabled="rowscurrent === null">上移</el-button>
                      <el-button icon="el-icon-bottom" type="primary" @click="handleRowsMove('Down')" :disabled="rowscurrent === null">下移</el-button>
                      <el-button icon="el-icon-delete" type="danger" @click="handleRowsMove('Delete')" :disabled="rowscurrent === null">删除</el-button>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
            <el-table
              height="50vh"
              ref="mattable"
              highlight-current-row
              :row-class-name="rowsetclassFun"
              @current-change="rowsCurrentChange"
              v-loading="crud.loading"
              lazy
              :data="crud.data"
              border
              stripe
              @select="crud.selectChange"
              @select-all="crud.selectAllChange"
              @selection-change="crud.selectionChangeHandler"
              @sort-change="handleSortEvent"
              style="width: 100%;">
              <el-table-column type="index" width="55" />
              <el-table-column prop="mat_name" show-overflow-tooltip label="素材" width="320" sortable="custom"></el-table-column>
              <el-table-column prop="pgm_len" label="节目长度" sortable="custom" show-overflow-tooltip>
                <template v-slot="scope">
                  <time-picker inputType="readonly" v-model="scope.row.pgm_len" />
                 </template>
              </el-table-column>
              <el-table-column prop="markin" label="入点" sortable="custom" show-overflow-tooltip>
                <template v-slot="scope">
                  <time-picker inputType="readonly" v-model="scope.row.markin" />
                 </template>
              </el-table-column>
              <el-table-column prop="markout" label="出点" sortable="custom" show-overflow-tooltip>
                <template v-slot="scope">
                  <time-picker inputType="readonly" v-model="scope.row.markout" />
                 </template>
              </el-table-column>
            </el-table>
          </div>

          <!--分页组件-->
<!--          <pagination /> -->
        </el-col>
      </el-row>

      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="closed">取消</el-button>
        <el-button type="primary" @click="submit">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import CRUD, { presenter, header, form, crud } from '@/components/Crud/crud'
import crudDevice from '@/api/pgmmanage/pgmlib.js' // 引入当前栏目的后端api
import commonMethods from '@/utils/commonMethods.js'
import { dateFormat } from '@/utils/commonFun.js'
// import pagination from '@/components/Crud/Pagination.vue' // 分页组件
import Sortable from 'sortablejs'

// 配置表单字段， 并设置字段初始值
const defaultForm = {
  mat_id: null,
  mat_name: null,
  mat_type: null,
  markin: 0,
  markout: 0,
  file_len: 0,
  s_date: dateFormat(new Date(), 'ymd'),
  e_date: dateFormat(new Date(), 'ymd'),
  creator: null,
  create_time: dateFormat(new Date(), 'ymd'),
  remark: null
}
export default {
  name: 'matdialog',
  cruds() { // 该方法，返回当前组件配置初始化后的实例对象
    return CRUD({ idField: 'pgmgrp_id', title: '节目组选择', url: 'pgmmanage/pgmgroup', query: { type: 0 }, crudMethod: { ...crudDevice }, sort: ['pgmgrp_id,asc'] })
  },
  mixins: [presenter(), header(), form(defaultForm), crud(), commonMethods],
  watch: {
    innerVisible(newV) {
      if (newV) {
        console.log(this.scopeRow)
        this.$nextTick(() => {
          // this.setDrag()
          this.query.type = this.scopeRow.pgm_id
          this.crud.toQuery()
        })
      }
    },
    'crud.data'(newV, oldV) {
      if (newV.length > 0) {
        let sum = 0
        newV.map(item => {
          sum += item.pgm_len
        })
        this.sumpgmLen = sum
      }
    }
  },
  data() {
    return {
      sumpgmLen: 0,
      visible: false,
      visibleL: true,
      rowscurrent: null,
      optionsType: [
        {
          mat_type_id: 0,
          mat_type_name: '根类型',
          children: []
        }
      ]
    }
  },
  props: {
    mattype: {
      type: String,
      default: 'all'
    },
    innerVisible: {
      type: Boolean,
      default: false
    },
    scopeRow: {
      type: Object,
      default: null
    }
  },
  created() {
  },
  mounted() {
    // console.log(this.$refs.dialogtreeone, 'abc')
  },
  methods: {
    rowsetclassFun(rowsobj) { // 单元行class 设置
      const { row, rowIndex } = rowsobj
      row.index = rowIndex // 把每行的索引放进row中
    },
    setDrag() {
      const el = this.$refs.mattable.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
      const that = this
      this.sortable = Sortable.create(el, {
        group: {
          name: 'shared',
          pull: 'clone',
          put: false // 不允许拖拽进这个列表
        },
        sort: false, // 设为false 禁止排序
        animation: 150,
        ghostClass: 'sortable-ghost',
        setData: function (/** DataTransfer */dataTransfer, /** HTMLElement */dragEl) {
          dataTransfer.setData('Text', dragEl.textContent) // `dataTransfer` object of HTML5 DragEvent
        },
        onEnd: evt => {
          if (evt.from === evt.to) return
          var oldIndex = evt.oldIndex
          // var $tr = evt.item
          var $oldtr = evt.clone

          const nextSlibing = $oldtr.nextSibling

          el.removeChild($oldtr) // 先删除留守的节点
          el.insertBefore(evt.item, nextSlibing) // 还原节点

          // 更新items 下次netTick重新还原虚拟DOM
          var item = that.crud.data.splice(oldIndex, 1)
          that.crud.data.splice(oldIndex, 0, item[0])

          this.$emit('dragchange', item[0]) // 将拖动的item 向父级传递
        }
      })
    },
    closed() {
      this.$emit('close')
    },
    async submit() {
      const mat_ids = this.crud.data.map(item => {
        return item.mat_id
      })
      // console.log(mat_ids)
      const { data: res } = await this.$http.post('pgmmanage/pgmgroup', {
        pgmgrp_id: this.scopeRow.pgm_id,
        mat_id: mat_ids.join(',')
      })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.message)
      }
      this.$emit('close', this.sumpgmLen)
    },
    rowsCurrentChange(rows) {
      this.rowscurrent = rows
    },

    // 排序点击
    handleSortEvent(sort) {
      const sortArr = { descending: 'desc', ascending: 'asc' }
      if (sort.order !== null) {
        this.crud.sort = sort.prop + ',' + sortArr[sort.order]
      } else {
        this.crud.sort = ''
      }
      this.crud.toQuery()
    },
    changetype(val) {
      this.crud.query.type = val
      this.crud.toQuery()
      this.$refs.cascader.dropDownVisible = false
    },
    handleTypeClick(data, node, el) {
      if (this.$refs.dialogtreeone.currentNode !== null) {
        this.$refs.dialogtreeone.currentNode.$el.setAttribute('class', 'el-tree-node')
      }
      el.$el.setAttribute('class', 'el-tree-node is-current is-focusable') // 设置选中
      if (data.mat_type_id === undefined) {
        this.query.type = 0
      } else {
        this.query.type = this.findNodeChildValArr(data, 'mat_type_id', []).join(',')
      }
      this.crud.toQuery()
    },
    async handleRowsMove(direction) {
      const rows = this.rowscurrent || null
      let targetRow, confirmresult
      switch (direction) {
        case 'Up':
          if (rows.index - 1 < 0) return this.$message.error('已移动到最顶部')
          targetRow = this.crud.data.splice(rows.index, 1)[0]
          this.crud.data.splice(rows.index - 1, 0, targetRow)
          break
        case 'Down':
          if (rows.index + 1 >= this.crud.data.length) return this.$message.error('已移动到最底部')
          targetRow = this.crud.data.splice(rows.index, 1)[0]
          this.crud.data.splice(rows.index + 1, 0, targetRow)
          break
        case 'Delete':
          confirmresult = await this.$confirm('确定要删除【 `' + rows.mat_name + '` 】节目吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            customClass: 'zdyIndex'
          }).catch(err => err)
          if (confirmresult !== 'confirm') {
            return false
            // return this.$message.info('您已取消了删除')
          }
          this.crud.data.splice(rows.index, 1)
          break
        default:
          return false
      }

      setTimeout(() => {
        this.$refs.mattable.setCurrentRow(this.crud.data[rows.index])
      }, 20)
    }
  }
}
</script>

<style lang="less">
  .animat {
    i {
      color: #0086B3;
    }
    animation: aname .8s 5;
  }
  .zdyIndex {
    z-index: 9999;
  }

  @keyframes aname{
    from{
      left: -12px;
    }
    to{
      left: -9px;
    }
  }
  .el-message-box__wrapper {
        position: fixed;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        text-align: center;
        z-index: 9999 !important;
  }
</style>
